<script setup>
	import {ref, toRefs} from 'vue'
    import menuApi from '@/api/sys/menu'
    import roleApi from '@/api/sys/role'

    //获取父组件的属性
    const props = defineProps({
        permDrawer: Boolean
    })
    const {permDrawer} = toRefs(props)

    //调用父组件的closeHandler方法
    const emits = defineEmits(['closeHandler'])
    //hasChange为true，需要更新列表
    const closeDrawer = (hasChange) => {
        emits('closeHandler',hasChange)
    }

    const permForm = ref({})
    const treeData = ref([])
    const treeRef = ref(null)
    let roleId = null
    //将子组件的init方法暴露给父组件
    const init = (id) => {
        roleId = id
        //获取菜单列表
        menuApi.getMenuTree().then(response => {
            treeData.value = response.data
        })

        //回显已经勾选的菜单id
        roleApi.getRoleDetailsById(id).then(response => {
            treeRef.value.setCheckedKeys(response.data.menuIds)
        })
    }
    defineExpose({init})

    //提交表单
    import { ElMessage } from 'element-plus'
    const submitForm = () => {
	    const menuIds = treeRef.value.getCheckedKeys()
        roleApi.assignMenusToRole(roleId,menuIds).then(response => {
            ElMessage({type: 'success',message: '操作成功',})
            closeDrawer(true)
        })
    }

</script>

<template>
	<el-drawer
			title="分配权限"
			v-model="permDrawer"
			width="600px"
            :before-close="closeDrawer">

		<el-form :model="permForm">
			<el-form-item>
				<el-tree
						:data="treeData"
						show-checkbox
						ref="treeRef"
						:default-expand-all=true
						node-key="id"
						:check-strictly=true
						:props="{children: 'children',label: 'title'}">
				</el-tree>
			</el-form-item>

			<el-form-item>
				<el-button @click="closeDrawer">关 闭</el-button>
				<el-button type="primary" @click="submitForm('permForm')">确 定</el-button>
			</el-form-item>
		</el-form>
	</el-drawer>
</template>
